<template>
    <div class="reports-container">
        <div class="header">
            <h2>报表管理</h2>
            <el-button type="primary" @click="showCreateDialog">创建报表</el-button>
        </div>

        <!-- 报表列表 -->
        <el-table
            v-loading="loading"
            :data="reports"
            style="width: 100%"
            border
        >
            <el-table-column prop="name" label="报表名称" />
            <el-table-column prop="type" label="报表类型">
                <template #default="{ row }">
                    {{ getReportTypeName(row.type) }}
                </template>
            </el-table-column>
            <el-table-column prop="data_source_name" label="数据源" />
            <el-table-column prop="status" label="状态">
                <template #default="{ row }">
                    <el-tag :type="getStatusType(row.status)">
                        {{ getStatusName(row.status) }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
                <template #default="{ row }">
                    <el-button
                        :icon="View"
                        circle
                        type="primary"
                        @click="viewReport(row)"
                        :disabled="row.status !== 'completed'"
                    />
                    <el-button
                        :icon="Download"
                        circle
                        type="success"
                        @click="handleExport(row)"
                        :disabled="row.status !== 'completed'"
                    />
                    <el-button
                        :icon="Delete"
                        circle
                        type="danger"
                        @click="handleDelete(row)"
                    />
                </template>
            </el-table-column>
        </el-table>

        <!-- 创建报表对话框 -->
        <el-dialog
            v-model="createDialogVisible"
            title="创建报表"
            width="500px"
        >
            <el-form
                ref="createFormRef"
                :model="createForm"
                :rules="rules"
                label-width="100px"
            >
                <el-form-item label="报表名称" prop="name">
                    <el-input v-model="createForm.name" />
                </el-form-item>
                <el-form-item label="报表类型" prop="type">
                    <el-select v-model="createForm.type" placeholder="请选择报表类型">
                        <el-option
                            v-for="type in reportTypes"
                            :key="type.value"
                            :label="type.label"
                            :value="type.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="数据源" prop="data_source">
                    <el-select v-model="createForm.data_source" placeholder="请选择数据源">
                        <el-option
                            v-for="source in dataSources"
                            :key="source.id"
                            :label="source.name"
                            :value="source.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="指标" prop="metrics">
                    <el-select
                        v-model="createForm.metrics"
                        multiple
                        placeholder="请选择分析指标"
                    >
                        <el-option
                            v-for="metric in metricOptions"
                            :key="metric.value"
                            :label="metric.label"
                            :value="metric.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="时间范围">
                    <el-date-picker
                        v-model="createForm.dateRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="createDialogVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="handleCreate"
                    :loading="submitting"
                >
                    创建
                </el-button>
            </template>
        </el-dialog>

        <!-- 查看报表对话框 -->
        <el-dialog
            v-model="viewDialogVisible"
            title="查看报表"
            width="80%"
            destroy-on-close
        >
            <div v-if="currentReport" class="report-content">
                <el-row :gutter="20">
                    <!-- 数据量趋势 -->
                    <el-col :span="24" v-if="currentReport.result?.data_volume">
                        <el-card class="chart-card">
                            <template #header>
                                <div class="card-header">
                                    <span>数据量趋势</span>
                                </div>
                            </template>
                            <div class="chart-container">
                                <v-chart :option="getDataVolumeOption" autoresize />
                            </div>
                        </el-card>
                    </el-col>

                    <!-- 互动趋势 -->
                    <el-col :span="24" v-if="currentReport.result?.engagement">
                        <el-card class="chart-card">
                            <template #header>
                                <div class="card-header">
                                    <span>互动趋势</span>
                                </div>
                            </template>
                            <div class="chart-container">
                                <v-chart :option="getEngagementOption" autoresize />
                            </div>
                        </el-card>
                    </el-col>

                    <!-- 用户活跃度 -->
                    <el-col :span="24" v-if="currentReport.result?.user_activity">
                        <el-card class="chart-card">
                            <template #header>
                                <div class="card-header">
                                    <span>用户活跃度</span>
                                </div>
                            </template>
                            <div class="chart-container">
                                <v-chart :option="getUserActivityOption" autoresize />
                            </div>
                        </el-card>
                    </el-col>

                    <!-- 内容分析 -->
                    <el-col :span="12" v-if="currentReport.result?.content_analysis">
                        <el-card class="chart-card">
                            <template #header>
                                <div class="card-header">
                                    <span>内容分析</span>
                                </div>
                            </template>
                            <div class="chart-container">
                                <v-chart :option="getContentAnalysisOption" autoresize />
                            </div>
                        </el-card>
                    </el-col>

                    <!-- 情感分析 -->
                    <el-col :span="12" v-if="currentReport.result?.sentiment">
                        <el-card class="chart-card">
                            <template #header>
                                <div class="card-header">
                                    <span>情感分析</span>
                                </div>
                            </template>
                            <div class="chart-container">
                                <v-chart :option="getSentimentOption" autoresize />
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>
            <div v-else class="no-data">
                <el-empty description="暂无报表数据" />
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { View, Download, Delete } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart, PieChart } from 'echarts/charts'
import {
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent,
    DataZoomComponent,
    ToolboxComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { analysisApi } from '@/api/analysis'
import 'echarts-wordcloud'

// 注册必需的组件
use([
    CanvasRenderer,
    LineChart,
    BarChart,
    PieChart,
    TitleComponent,
    TooltipComponent,
    LegendComponent,
    GridComponent,
    DataZoomComponent,
    ToolboxComponent
])

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const createDialogVisible = ref(false)
const viewDialogVisible = ref(false)
const reports = ref([])
const dataSources = ref([])
const currentReport = ref(null)
const createFormRef = ref(null)

// 表单数据
const createForm = ref({
    name: '',
    type: '',
    data_source: '',
    metrics: [],
    dateRange: []
})

// 报表类型选项
const reportTypes = [
    { value: 'overview', label: '数据概览报表' },
    { value: 'trend', label: '趋势分析报表' },
    { value: 'user', label: '用户分析报表' },
    { value: 'content', label: '内容分析报表' },
    { value: 'custom', label: '自定义报表' }
]

// 指标选项
const metricOptions = [
    { value: 'data_volume', label: '数据量' },
    { value: 'engagement', label: '互动数据' },
    { value: 'user_activity', label: '用户活跃度' },
    { value: 'content_analysis', label: '内容分析' },
    { value: 'sentiment', label: '情感分析' }
]

// 表单验证规则
const rules = {
    name: [
        { required: true, message: '请输入报表名称', trigger: 'blur' }
    ],
    type: [
        { required: true, message: '请选择报表类型', trigger: 'change' }
    ],
    data_source: [
        { required: true, message: '请选择数据源', trigger: 'change' }
    ],
    metrics: [
        { required: true, message: '请选择至少一个指标', trigger: 'change' }
    ]
}

// 计算属性：图表配置
const getDataVolumeOption = computed(() => {
    if (!currentReport.value?.result?.data_volume) {
        console.log('No data volume data available')
        return {}
    }
    
    const data = currentReport.value.result.data_volume
    console.log('Preparing data volume chart with data:', data)
    
    return {
        grid: {
            top: 40,
            right: 40,
            bottom: 60,
            left: 60,
            containLabel: true
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        xAxis: {
            type: 'category',
            data: data.dates || [],
            axisLabel: {
                rotate: 45,
                interval: 0
            }
        },
        yAxis: {
            type: 'value',
            name: '数据量'
        },
        series: [{
            name: '数据量',
            type: 'line',
            data: data.values || [],
            smooth: true,
            showSymbol: true,
            areaStyle: {
                opacity: 0.3
            }
        }]
    }
})

const getEngagementOption = computed(() => {
    if (!currentReport.value?.result?.engagement) {
        console.log('No engagement data available')
        return {}
    }
    
    const data = currentReport.value.result.engagement
    console.log('Preparing engagement chart with data:', data)
    
    return {
        grid: {
            top: 60,
            right: 40,
            bottom: 60,
            left: 60,
            containLabel: true
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        legend: {
            top: 10,
            data: ['评论', '点赞', '转发']
        },
        xAxis: {
            type: 'category',
            data: data.dates || [],
            axisLabel: {
                rotate: 45,
                interval: 0
            }
        },
        yAxis: {
            type: 'value',
            name: '数量'
        },
        series: [
            {
                name: '评论',
                type: 'line',
                data: data.comments || [],
                smooth: true
            },
            {
                name: '点赞',
                type: 'line',
                data: data.likes || [],
                smooth: true
            },
            {
                name: '转发',
                type: 'line',
                data: data.reposts || [],
                smooth: true
            }
        ]
    }
})

const getUserActivityOption = computed(() => {
    if (!currentReport.value?.result?.user_activity) {
        console.log('No user activity data available')
        return {}
    }
    
    const data = currentReport.value.result.user_activity
    console.log('Preparing user activity chart with data:', data)
    
    return {
        grid: {
            top: 40,
            right: 40,
            bottom: 60,
            left: 60,
            containLabel: true
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            }
        },
        xAxis: {
            type: 'category',
            data: data.dates || [],
            axisLabel: {
                rotate: 45,
                interval: 0
            }
        },
        yAxis: {
            type: 'value',
            name: '活跃用户数'
        },
        series: [{
            name: '活跃用户',
            type: 'line',
            data: data.values || [],
            smooth: true,
            areaStyle: {
                opacity: 0.3
            }
        }]
    }
})

const getContentAnalysisOption = computed(() => {
    if (!currentReport.value?.result?.content_analysis) {
        console.log('No content analysis data available')
        return {}
    }
    
    const data = currentReport.value.result.content_analysis
    console.log('Preparing content analysis chart with data:', data)
    
    return {
        tooltip: {
            show: true,
            formatter: function(params) {
                return `${params.data.name}: ${params.data.value}`
            }
        },
        series: [{
            type: 'wordCloud',
            shape: 'circle',
            left: 'center',
            top: 'center',
            width: '90%',
            height: '90%',
            right: null,
            bottom: null,
            sizeRange: [12, 60],
            rotationRange: [-90, 90],
            rotationStep: 45,
            gridSize: 8,
            drawOutOfBound: false,
            layoutAnimation: true,
            textStyle: {
                fontFamily: 'sans-serif',
                fontWeight: 'bold',
                color: function () {
                    return 'rgb(' + [
                        Math.round(Math.random() * 160),
                        Math.round(Math.random() * 160),
                        Math.round(Math.random() * 160)
                    ].join(',') + ')'
                }
            },
            emphasis: {
                focus: 'self',
                textStyle: {
                    shadowBlur: 10,
                    shadowColor: '#333'
                }
            },
            data: data.topics || []
        }]
    }
})

const getSentimentOption = computed(() => {
    if (!currentReport.value?.result?.sentiment) {
        console.log('No sentiment data available')
        return {}
    }
    
    const data = currentReport.value.result.sentiment
    console.log('Preparing sentiment chart with data:', data)
    
    return {
        tooltip: {
            trigger: 'item',
            formatter: '{b}: {c} ({d}%)'
        },
        legend: {
            orient: 'vertical',
            left: 'left',
            top: 'middle'
        },
        series: [{
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '50%'],
            avoidLabelOverlap: true,
            itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
            },
            label: {
                show: true,
                formatter: '{b}: {c} ({d}%)'
            },
            emphasis: {
                label: {
                    show: true,
                    fontSize: '16',
                    fontWeight: 'bold'
                }
            },
            data: [
                { value: data.positive || 0, name: '正面' },
                { value: data.neutral || 0, name: '中性' },
                { value: data.negative || 0, name: '负面' }
            ]
        }]
    }
})

// 方法
const fetchReports = async () => {
    try {
        loading.value = true
        const response = await analysisApi.getReports()
        console.log('Fetched reports:', response)
        reports.value = Array.isArray(response) ? response : (response?.results || [])
    } catch (error) {
        console.error('Error fetching reports:', error)
        ElMessage.error('获取报表列表失败')
        reports.value = []
    } finally {
        loading.value = false
    }
}

const fetchDataSources = async () => {
    try {
        const response = await analysisApi.getDataSources()
        console.log('Fetched data sources:', response)
        dataSources.value = Array.isArray(response) ? response : (response?.results || [])
    } catch (error) {
        console.error('Error fetching data sources:', error)
        ElMessage.error('获取数据源列表失败')
        dataSources.value = []
    }
}

const showCreateDialog = () => {
    createForm.value = {
        name: '',
        type: '',
        data_source: '',
        metrics: [],
        dateRange: []
    }
    createDialogVisible.value = true
}

const handleCreate = async () => {
    if (!createFormRef.value) return
    
    try {
        await createFormRef.value.validate()
        
        submitting.value = true
        const [startDate, endDate] = createForm.value.dateRange
        
        const data = {
            name: createForm.value.name,
            type: createForm.value.type,
            data_source: createForm.value.data_source,
            metrics: createForm.value.metrics,
            start_date: startDate,
            end_date: endDate
        }
        
        console.log('Creating report with data:', data)
        await analysisApi.createReport(data)
        
        ElMessage.success('报表创建成功')
        createDialogVisible.value = false
        fetchReports()
    } catch (error) {
        console.error('Error creating report:', error)
        ElMessage.error('创建报表失败')
    } finally {
        submitting.value = false
    }
}

const viewReport = async (report) => {
    try {
        console.log('Viewing report:', report)
        const response = await analysisApi.getReportDetail(report.id)
        console.log('Report detail response:', response)
        
        if (!response) {
            ElMessage.warning('未获取到报表数据')
            return
        }
        
        if (!response.result) {
            ElMessage.warning('报表数据未生成完成')
            return
        }
        
        // 打印每个图表的数据
        if (response.result.data_volume) {
            console.log('Data volume data:', response.result.data_volume)
        }
        if (response.result.engagement) {
            console.log('Engagement data:', response.result.engagement)
        }
        if (response.result.user_activity) {
            console.log('User activity data:', response.result.user_activity)
        }
        if (response.result.content_analysis) {
            console.log('Content analysis data:', response.result.content_analysis)
        }
        if (response.result.sentiment) {
            console.log('Sentiment data:', response.result.sentiment)
        }
        
        currentReport.value = response
        viewDialogVisible.value = true
    } catch (error) {
        console.error('Error viewing report:', error)
        ElMessage.error('获取报表详情失败')
    }
}

const handleExport = async (report) => {
    try {
        const response = await analysisApi.exportReport(report.id)
        const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `${report.name}.xlsx`
        link.click()
        window.URL.revokeObjectURL(url)
    } catch (error) {
        console.error('Error exporting report:', error)
        ElMessage.error('导出报表失败')
    }
}

const handleDelete = (report) => {
    ElMessageBox.confirm(
        '确定要删除这个报表吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            await analysisApi.deleteReport(report.id)
            ElMessage.success('删除成功')
            fetchReports()
        } catch (error) {
            console.error('Error deleting report:', error)
            ElMessage.error('删除失败')
        }
    })
}

const getReportTypeName = (type) => {
    const reportType = reportTypes.find(t => t.value === type)
    return reportType ? reportType.label : type
}

const getStatusType = (status) => {
    const statusMap = {
        processing: 'warning',
        completed: 'success',
        failed: 'danger'
    }
    return statusMap[status] || 'info'
}

const getStatusName = (status) => {
    const statusMap = {
        processing: '生成中',
        completed: '已完成',
        failed: '失败'
    }
    return statusMap[status] || status
}

// 生命周期钩子
onMounted(() => {
    fetchReports()
    fetchDataSources()
})
</script>

<style scoped>
.reports-container {
    padding: 20px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.report-list-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.card-header h3 {
    margin: 0;
}

.report-content {
    padding: 20px;
}

.chart-card {
    margin-bottom: 20px;
}

.chart-container {
    width: 100%;
    height: 400px;
    position: relative;
}

:deep(.echarts) {
    width: 100% !important;
    height: 100% !important;
}

.el-button-group {
    display: flex;
    gap: 8px;
}

@media screen and (max-width: 768px) {
    .reports-container {
        padding: 12px;
    }
    
    .el-button-group {
        flex-direction: column;
    }
    
    .chart-container {
        height: 300px;
    }
}

.no-data {
    padding: 40px;
    text-align: center;
}
</style>